<?php if(!defined('SIDELOADED')) { echo 'Direct access is not allowed.'; }

if(!class_exists('Database')) { user_error('User{} requires Database{} to function.', E_USER_ERROR); }

class User {
  
  private $db,
          $userInfo,
          $userPerms,
          $userGames;
  
  public function __construct($id) {
    
    $this->db = new Database();
    
    // Get the user's main information
    $query = 'SELECT * FROM `users` WHERE `id`="' . $id . '";';
    $this->db->Run($query);
    $result = $this->db->Result();
    if($result !== false) { foreach($result as $k => $v) { $this->userInfo[$k] = $v; } }
    
    $query = 'SELECT * FROM `users_perms` WHERE `id`="' . $id . '";';
    $this->db->Run($query);
    $result = $this->db->Result();
    if($result !== false) { foreach($result as $k => $v) { $this->userPerms[$k] = $v; } }
    
    $query = 'SELECT * FROM `users_games` WHERE `id`="' . $id . '";';
    $this->db->Run($query);
    $result = $this->db->Result();
    if($result !== false) { foreach($result as $k => $v) { $this->userGames[$k] = $v; } }
    
  }
  
  public function __get($name) {
    
    return $this->userInfo[$name];
    
  }
  
  public function Perms($permissionset) {
    
    return $this->userPerms[$permissionset];
    
  }
  
  public function Games($game) {
    
    return $this->userGames[$game];
    
  }
  
  public static function Hash($password, $salt) {
    
    return sha1($salt . $password . 'hardSalt<3');
    
  }
  
  public static function Register($username, $password, $email, $key) {
    
    $db = new Database();
    
    $salt = substr(md5(rand(0, date('Y')) . microtime()), date('m'), 6);
    
    $db->Insert('users', array(
      'email' => $db->Escape($email),
      'password' => self::Hash($password, $salt),
      'salt' => $salt,
      'account' => $db->Escape($username),
      'regdate' => time()
    ));
    
    $id = $db->Id();
    
    $db->Query('UPDATE `users_regkeys` SET `used`="' . $id . '" WHERE `key`="' . $db->Escape($key) . '";');
    $db->Query('INSERT INTO `users_perms`(`id`) VALUES (' . $id . ');');
    $db->Query('INSERT INTO `users_games`(`id`) VALUES (' . $id . ');');
    
    return $id;
    
  }
  
}
